package com.lagou.homework.servlet;

import com.lagou.homework.model.User;
import com.lagou.homework.service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 页面登录
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //实现向服务器发送请求的功能
        String name = request.getParameter("userName");
        System.out.println("获取到的用户名是： " +name);
        String password = request.getParameter("password");
        System.out.println("获取到的密码是： " +password);

        //创建UserService类型的对象进行数据的校验
        UserService userService = new UserService();
        User user = userService.userLoginService(new User(name,password));

        if(null==user){
            System.out.println("登录失败！");
            request.setAttribute("error","登陆失败，用户名或者密码错误...");
            //登录失败  通过转向的方式  继续停留在登陆页面
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            requestDispatcher.forward(request,response);
        }else{
            System.out.println("登录成功！");
            //获取session对象
            request.getSession().setAttribute("user",user);
            //实现页面的跳转 重定向
            response.sendRedirect("face.html");
        }

    }




    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
